import React, { Component } from 'react'
import { Space, Select, Button, Typography } from 'antd';
import { connect } from "react-redux"
import { addAction, subtractAction, addAsyncAction } from "../redux/count_action"
const { Option } = Select;
const { Title } = Typography;
// 接收redux中最新的状态通过props传递给UI组件,下面是简写形式
const mapStateToProps = state => (
    {
        count: state
    }
)
// 声明一个方法对象，里面存放这操作redux状态的action方法
const mapDispatchToProps = {
    addAction, subtractAction, addAsyncAction
}


class Count extends Component {
    state = {
        // 下拉框绑定值
        selectVal: 1
    }

    // 改变下拉触发
    handleChange = (value) => {
        this.setState({
            selectVal: +value
        })
    }
    // 加
    add = () => {
        console.log(this.props);
        const { selectVal } = this.state
        this.props.addAction(selectVal)
    }
    // 减
    subtract = () => {
        const { selectVal } = this.state
        this.props.subtractAction(selectVal)
    }
    // 奇数加
    addIfOdd = () => {
        const { selectVal } = this.state
        if (this.props.count % 2 !== 0) {
            this.props.addAction(selectVal)
        }
    }

    addIfAsync = () => {
        const { selectVal } = this.state
        this.props.addAsyncAction(selectVal, 1000)
    }


    render() {
        return (
            <div>
                <div>
                    {/* store.getState() 从redux中获取数据 */}
                    <Title level={4}>当前数据和:{this.props.count}</Title>
                </div>

                <div>
                    <Space size='small'>
                        <Select defaultValue={this.state.selectVal} style={{ width: 150 }} onChange={this.handleChange}>
                            <Option value="1">1</Option>
                            <Option value="2">2</Option>
                            <Option value="3">3</Option>
                        </Select>
                        <Button type="primary" onClick={this.add}>加</Button>
                        <Button type="primary" onClick={this.subtract}>减</Button>
                        <Button type="primary" onClick={this.addIfOdd}>奇数加</Button>
                        <Button type="primary" onClick={this.addIfAsync}>异步增加</Button>
                    </Space>
                </div>
            </div>
        )
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Count)
